﻿using CTP.CRM.Core.Common.Dto;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.DependencyInjection;
using CTP.CRM.Core.Common.Attributes;

namespace CTP.CRM.Core.Filter
{
    public class UnifyResultFilter : IAsyncActionFilter, IFilterMetadata, ISingletonDependency
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            ActionExecutedContext actionContext = await next();
            if (actionContext.Exception == null && actionContext.ModelState.IsValid && !context.HttpContext.Request.Path.ToString().StartsWith("/api/abp") && !context.HttpContext.Request.Path.ToString().StartsWith("/api/app"))
            {
                IActionResult result = actionContext.Result;
                if ((!(result is ObjectResult obj) || !(obj?.Value?.GetType() == typeof(UnifyDtmResultDto))) && !context.ActionDescriptor.EndpointMetadata.Any((object m) => m.GetType() == typeof(CustomerResultAttribute)) && CheckVaildResult(actionContext.Result, out object data))
                {
                    actionContext.Result = new JsonResult(new UnifyResultDto(200.ToString(), "操作成功", data));
                }
            }
        }

        private static bool CheckVaildResult(IActionResult result, out object data)
        {
            data = null;
            if (1 == 0)
            {
            }

            bool flag = result is EmptyResult || (!(result is ViewResult) && !(result is PartialViewResult) && !(result is FileResult) && !(result is ChallengeResult) && !(result is SignInResult) && !(result is SignOutResult) && !(result is RedirectToPageResult) && !(result is RedirectToRouteResult) && !(result is RedirectResult) && !(result is RedirectToActionResult) && !(result is LocalRedirectResult) && !(result is ForbidResult) && !(result is ViewComponentResult) && !(result is PageResult) && !(result is StatusCodeResult));
            if (1 == 0)
            {
            }

            bool flag2 = flag;
            if (flag2)
            {
                if (result is ContentResult contentResult)
                {
                    data = contentResult.Content;
                }
                else if (result is ObjectResult objectResult)
                {
                    if (objectResult.Value == null)
                    {
                        return true;
                    }

                    if (objectResult.Value.GetType() == typeof(UnifyResultDto) || (objectResult.Value.GetType().IsGenericType && objectResult.Value.GetType().GetGenericTypeDefinition() == typeof(UnifyResultDto<>)))
                    {
                        return false;
                    }

                    data = objectResult.Value;
                }
                else
                {
                    data = null;
                }
            }

            return flag2;
        }
    }
}
